// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/overview' 
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/overview', 
    name: 'Overview',
    component: () => import('@/views/overview.vue'),
    meta: { requiresAuth: true }  // 添加：需要认证
  },
  {
    path: '/devices',
    name: 'DeviceManagement',
    component: () => import('@/views/DeviceManagement.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/training',
    name: 'TrainingConfig', 
    component: () => import('@/views/TrainingConfig.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/tracking',
    name: 'TrainingTracking',
    component: () => import('@/views/TrainingTracking.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/logs',
    name: 'TrainingLogs',
    component: () => import('@/views/TrainingLogs.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/overview'  // 修改：404也重定向到总览
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫保持不变
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('auth_token')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.requiresGuest && token) {
    next('/overview')  // 修改：已登录用户重定向到总览
  } else {
    next()
  }
})

export default router